package com.zzyl.nursing.service.impl;

import java.time.LocalDate;
import java.time.Period;
import java.util.List;

import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.nursing.domain.*;
import com.zzyl.nursing.dto.CheckInApplyDto;
import com.zzyl.nursing.dto.CheckInConfigDto;
import com.zzyl.nursing.dto.ElderFamilyDto;
import com.zzyl.nursing.mapper.*;
import com.zzyl.nursing.utils.CodeGenerator;
import com.zzyl.nursing.vo.CheckInConfigVo;
import com.zzyl.nursing.vo.CheckInDetailVo;
import com.zzyl.nursing.vo.CheckInElderVo;
import com.zzyl.nursing.vo.ElderFamilyVo;
import lombok.val;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.service.ICheckInService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;

import static cn.hutool.core.date.DateTime.now;

/**
 * 入住Service业务层处理
 * 
 * @author ruoyi
 * @date 2024-10-07
 */
@Service
public class CheckInServiceImpl extends ServiceImpl<CheckInMapper, CheckIn> implements ICheckInService
{
    @Autowired
    private CheckInMapper checkInMapper;

    @Autowired
    private ElderMapper elderMapper;

    @Autowired
    private BedMapper bedMapper;

    @Autowired
    private ContractMapper contractMapper;

    @Autowired
    private CheckInConfigMapper checkInConfigMapper;


    /**
     * 查询入住
     * 
     * @param id 入住主键
     * @return 入住
     */
    @Override
    public CheckIn selectCheckInById(Long id)
    {
        return getById(id);
    }

    /**
     * 查询入住列表
     * 
     * @param checkIn 入住
     * @return 入住
     */
    @Override
    public List<CheckIn> selectCheckInList(CheckIn checkIn)
    {
        return checkInMapper.selectCheckInList(checkIn);
    }

    /**
     * 新增入住
     * 
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int insertCheckIn(CheckIn checkIn)
    {
        return save(checkIn) ? 1 : 0;
    }

    /**
     * 修改入住
     * 
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int updateCheckIn(CheckIn checkIn)
    {
        return updateById(checkIn) ? 1 : 0;
    }

    /**
     * 批量删除入住
     * 
     * @param ids 需要删除的入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInByIds(Long[] ids)
    {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 删除入住信息
     * 
     * @param id 入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInById(Long id)
    {
        return removeById(id) ? 1 : 0;
    }


    /*
     * 提交入住申请
     * @param checkInApplyDto 入住申请人信息、合同信息等
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void apply(CheckInApplyDto checkInApplyDto) {
        //1.校验老人是否已入住,如果入住,则提示错误
        LambdaQueryWrapper<Elder> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Elder::getIdCardNo, checkInApplyDto.getCheckInElderDto().getIdCardNo());
        queryWrapper.eq(Elder::getStatus, 1);

        Elder elder = elderMapper.selectOne(queryWrapper);
        if(ObjectUtils.isNotNull(elder)){
            throw new BaseException("老人已入住,无法再入住");
        }
        //2.老人没有入住,更新床位状态为已入住
        //根据床位id查询床位对象
        Bed bed = bedMapper.selectById(checkInApplyDto.getCheckInConfigDto().getBedId());
        bed.setBedStatus(1);
        //入住配置DTO
//        CheckInConfigDto checkInConfigDto = checkInApplyDto.getCheckInConfigDto();
//        bed.setId(checkInConfigDto.getBedId());
//        bed.setRoomId(checkInConfigDto.getRoomId());

        bedMapper.updateById(bed);

        //3.新增或更新老人信息
        elder = insertOrUpdateElder(checkInApplyDto,bed);

        //4.新增签约办理
        insertContract(checkInApplyDto,elder);

        //5.新增入住信息
        CheckIn checkIn = insertCheckInInfo(checkInApplyDto,elder,bed);

        //6.新增入住配置
        insertCheckInConfig(checkInApplyDto,checkIn);
    }

    /**
     * 保存入住配置信息
     * @param checkInApplyDto
     * @param checkIn
     */
    private void insertCheckInConfig(CheckInApplyDto checkInApplyDto, CheckIn checkIn) {
        CheckInConfig checkInConfig = new CheckInConfig();
        BeanUtils.copyProperties(checkInApplyDto.getCheckInConfigDto(), checkInConfig);
        checkInConfig.setCheckInId(checkIn.getId());
        checkInConfigMapper.insert(checkInConfig);
    }

    /**
     * 保存入住信息
     * @param checkInApplyDto
     * @param elder
     * @param bed
     */
    private CheckIn insertCheckInInfo(CheckInApplyDto checkInApplyDto, Elder elder, Bed bed) {
        CheckIn checkIn = new CheckIn();
//        BeanUtils.copyProperties(checkInApplyDto.getCheckInConfigDto(), checkIn);
        checkIn.setNursingLevelName(checkInApplyDto.getCheckInConfigDto().getNursingLevelName());
        checkIn.setElderId(elder.getId());
        checkIn.setElderName(elder.getName());
        checkIn.setBedNumber(bed.getBedNumber());
        checkIn.setIdCardNo(elder.getIdCardNo());
        checkIn.setStartDate(checkInApplyDto.getCheckInConfigDto().getStartDate());
        checkIn.setEndDate(checkInApplyDto.getCheckInConfigDto().getEndDate());
        //保存家属信息列表
        checkIn.setRemark(JSON.toJSONString(checkInApplyDto.getElderFamilyDtoList()));
        checkInMapper.insert(checkIn);
        return checkIn;
    }

    /**
     * 签约办理
     * @param checkInApplyDto
     * @param elder
     */
    private void insertContract(CheckInApplyDto checkInApplyDto, Elder elder) {
        Contract contract = new Contract();
        BeanUtils.copyProperties(checkInApplyDto.getCheckInContractDto(), contract);
        contract.setElderId(Integer.valueOf(String.valueOf(elder.getId())));
        contract.setElderName(elder.getName());

        CheckInConfigDto checkInConfigDto = checkInApplyDto.getCheckInConfigDto();
        contract.setStartDate(checkInConfigDto.getStartDate());
        contract.setEndDate(checkInConfigDto.getEndDate());

        //生成合同编号
        contract.setContractNumber("HT" + CodeGenerator.generateContractNumber());
        contractMapper.insert(contract);
    }

    /*
    * 新增或更新老人信息
    * @param checkInApplyDto
    * @param bed
     */
    private Elder insertOrUpdateElder(CheckInApplyDto checkInApplyDto, Bed bed) {
        //准备老人对象信息
        Elder elder = new Elder();
        BeanUtils.copyProperties(checkInApplyDto.getCheckInElderDto(), elder);
        elder.setBedId(bed.getId());
        elder.setBedNumber(bed.getBedNumber());
        //查询老人是否曾经入住过
        LambdaQueryWrapper<Elder> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Elder::getIdCardNo, checkInApplyDto.getCheckInElderDto().getIdCardNo());
        queryWrapper.ne(Elder::getStatus, 1);
        Elder elderInDb = elderMapper.selectOne(queryWrapper);

        if (ObjectUtils.isNull(elderInDb)){
            //新增
            elderMapper.insertElder(elder);
        }else {
            //更新
            elderMapper.updateById(elder);
        }
        return elder;
    }




    /**
     * 查询入住详情
     * @param id
     * @return
     */
    @Override
    public CheckInDetailVo detail(Long id) {
        CheckInDetailVo checkInDetailVo = new CheckInDetailVo();
        //根据入住表的id查询入住信息详情
        CheckIn checkIn = checkInMapper.selectCheckInById(id);
        //根据入住表中的信息获取老人id
        Long elderId = checkIn.getElderId();
        //根据老人id查询老人的各种信息
        //1.查询老人信息
        Elder elder = elderMapper.selectById(elderId);
        CheckInElderVo checkInElderVo = new CheckInElderVo();//老人对象
        //计算老人年龄
        String birthday =elder.getBirthday();
        int age = Period.between(LocalDate.parse(birthday), LocalDate.now()).getYears();
        //将老人信息封装到对象中
        BeanUtils.copyProperties(elder, checkInElderVo);
        checkInElderVo.setAge(age);

        //2.查询老人家属信息
        //获取到家属信息(JSON)
        String remark = checkIn.getRemark();
        List<ElderFamilyVo> elderFamilyVoList = JSON.parseArray(remark, ElderFamilyVo.class);

        //3.查询老人入住配置信息
        CheckInConfigVo checkInConfigVo = new CheckInConfigVo();//配置对象
        //查询入住配置信息的id
        Long checkInConfigId = checkInConfigMapper.selectConfigId(id);
        //根据id获取到入住表信息
        CheckInConfig checkInConfig = checkInConfigMapper.selectCheckInConfigById(checkInConfigId);
        //拷贝到配置对象中
        BeanUtils.copyProperties(checkInConfig, checkInConfigVo);

        //查询入住楼层
        checkInConfigVo.setBedNumber(checkIn.getBedNumber());
        //存入入住表的开始结束时间
        checkInConfigVo.setStartDate(checkIn.getStartDate());
        checkInConfigVo.setEndDate(checkIn.getEndDate());

        //4.查询老人合同
        //根据老人id来查合同的id
        Long contractId = contractMapper.selectContractId(elderId);
        //根据合同id来查询合同信息
        Contract contract = contractMapper.selectContractById(contractId);

        //把信息都存入到checkInDetailVo
        checkInDetailVo.setCheckInElderVo(checkInElderVo);
        checkInDetailVo.setElderFamilyVoList(elderFamilyVoList);
        checkInDetailVo.setCheckInConfigVo(checkInConfigVo);
        checkInDetailVo.setContract(contract);
        return checkInDetailVo;
    }
}
